package com.hope.aimouse;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;

public class KeyMonitorService extends Service {
    private static final String TAG = "KeyMonitorService";
    private boolean isRunning = false;

    @Override
    public void onCreate() {
        super.onCreate();
        startKeyMonitor();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 确保服务不会被系统杀死
        return START_STICKY;
    }

    private void startKeyMonitor() {
        isRunning = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 打开输入设备
                    Process process = Runtime.getRuntime().exec("su");
                    DataOutputStream os = new DataOutputStream(process.getOutputStream());
                    // 监听输入事件
                    os.writeBytes("getevent\n");
                    os.flush();

                    // 读取输入事件
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(process.getInputStream()));
                    String line;
                    while (isRunning && (line = reader.readLine()) != null) {
                        // 解析输入事件
                        if (line.contains("KEY_F10")) {  // 检测F10按键
                            // 在这里处理F10按键事件
                            handleF10KeyPress();
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Error monitoring keys: " + e.getMessage());
                }
            }
        }).start();
    }

    private void handleF10KeyPress() {
        // 在主线程中处理按键事件
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                // 这里添加F10按键的处理逻辑
                // 例如：启动应用、截图等
                Toast.makeText(getApplicationContext(),
                        "F10 Pressed", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
